import math
import os
import re

import cv2
from cv2.cv2 import VideoWriter_fourcc
from PIL import Image
from arcface.engine import MOK, ASF_SingleFaceInfo
import numpy as np

def resizeImage(img2):
    sp = img2.shape
    img = cv2.resize(img2, (sp[1] // 4 * 4, sp[0] // 4 * 4))
    return img
def readImage(filePath):
    img = cv2.imread(filePath)
    return img
def showImage(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    pass
def getFeature(face_engine,img):
    #img = imageUtils.readImage(path)
    #print("读图",img)
    #人脸检测
    res,detectedFaces1 = face_engine.ASFDetectFaces(img)
    print("detect face result :", detectedFaces1.faceNum)
    if res == MOK:
        single_detected_face1 = ASF_SingleFaceInfo()
        single_detected_face1.faceRect = detectedFaces1.faceRect[0]
        single_detected_face1.faceOrient = detectedFaces1.faceOrient[0]
        res, face_feature1 = face_engine.ASFFaceFeatureExtract(img, single_detected_face1)
        print("face_feature is:",face_feature1.featureSize,face_feature1.feature)
        print("识别结果res is",res,type(face_feature1))
        if (res != MOK):
            print("ASFFaceFeatureExtract 1 fail: {}".format(res))
        return face_feature1
    else:
        print("dected face error")
def getfeatures(face_engine,img,face_list):
    fail_count = 0
    #print("face_list size ", len(face_list))
    face_new_list = []
    for i in range(len(face_list)):
        feature = face_list[i]
        #print("getfeatures is ",i,feature.bound)
        #print(type(feature.bound))
        single_detected_face1 = ASF_SingleFaceInfo()
        #print(type(single_detected_face1.faceRect))
        single_detected_face1.faceRect = feature.bound
        single_detected_face1.faceOrient = feature.orient
        res, face_feature1 = face_engine.ASFFaceFeatureExtract(img, single_detected_face1)
        if (res != MOK):
            fail_count +=1
            feature.featureSize=0
            print("ASFFaceFeatureExtract 1 fail: {}".format(res))
        else:
            feature.feature = face_feature1
            feature.featureSize = face_feature1.featureSize
        face_new_list.append(feature)
        #print("res",res)
        #print("getfeatures",feature.featureSize)

    return fail_count,face_new_list
#图片转视频
def pics2video(imgPath,videoPath):
    images = os.listdir(imgPath)
    images.sort(key=lambda x: int(re.findall(r"\d+", x)[0]))
    fps = 20
    fourcc = VideoWriter_fourcc(*"mp4v")
    imagepath = os.path.join(imgPath,images[0])
    image = Image.open(imagepath)
    videoWriter = cv2.VideoWriter(videoPath, fourcc, fps, image.size)
    for im_name in range(len(images)):
        imagepath = os.path.join(imgPath, images[im_name])
        frame = cv2.imread(imagepath)  # 这里的路径只能是英文路径
        # frame = cv2.imdecode(np.fromfile((imgPath + images[im_name]), dtype=np.uint8), 1)  # 此句话的路径可以为中文路径
        print(im_name)
        videoWriter.write(frame)
    print("图片转视频结束")
    videoWriter.release()
    cv2.cv2.destroyAllWindows()

    pass
# box的框为x,y,w,h
def mergeImage(img,boxes):
    outImage = np.zeros(img.shape,img.dtype)
    for box in boxes:
        print('box is ',box)
        print('box 0 is ',box[0])
        outImage[box[1]:box[3], box[0]:box[2]] = img[box[1]:box[3], box[0]:box[2]]
        #cv2.imshow('copy3', outImage)
        #cv2.waitKey(0)
        #cv2.destroyAllWindows()
    return outImage
# 针对大图进行缩放
def smallPic(image,imageSize):
    height, width = image.shape[0], image.shape[1]
    i =1
    if height > width:
        i=2
    print('height ',i,width,height)
    sizemax = max(height,width)
    ratio = imageSize/sizemax
    new_width = int(width *ratio) if i == 2 else (int(height *ratio))
    shape = (new_width,imageSize) if i == 2 else (imageSize,new_width)

    if ratio >=1:
        img = cv2.resize(image, shape, interpolation=cv2.INTER_LINEAR)
    else:
        img = cv2.resize(image, shape, interpolation=cv2.INTER_AREA)
    return img
def BiLinear_interpolation(img,dstH,dstW):
     scrH,scrW,_=img.shape
     img=np.pad(img,((0,1),(0,1),(0,0)),'constant')
     retimg=np.zeros((dstH,dstW,3),dtype=np.uint8)
     for i in range(dstH):
         for j in range(dstW):
             scrx=(i+1)*(scrH/dstH)-1
             scry=(j+1)*(scrW/dstW)-1
             x=math.floor(scrx)
             y=math.floor(scry)
             u=scrx-x
             v=scry-y
             retimg[i,j]=(1-u)*(1-v)*img[x,y]+u*(1-v)*img[x+1,y]+(1-u)*v*img[x,y+1]+u*v*img[x+1,y+1]
     return retimg
def ratiopic(image,imageSize):
    height, width = image.shape[0], image.shape[1]
    i = 1
    if height > width:
        i = 2
    print('height ', i, width, height)
    sizemax = max(height, width)
    ratio = imageSize / sizemax
    new_width = int(width * ratio) if i == 2 else (int(height * ratio))
    shape = (new_width, imageSize) if i == 2 else (imageSize, new_width)

    #img = cv2.resize(image, shape, interpolation=cv2.INTER_AREA)
    return BiLinear_interpolation(image,shape[0],shape[1])
if __name__ == '__main__':
    img1 = cv2.imread("../images/1.jpg")
    img2 = cv2.imread("../images/a1-face/102.png")
    imgPath = 'C:\\test\\docker\\var\\aiparents\\test\\video\\private\\record-video'
    videoPath = 'C:\\test\\docker\\var\\aiparents\\test\\video\\private\\test.mp4'
    #pics2video(imgPath,videoPath)
    print(img1)
    imagesource = "C:/test/docker/var/aiparents\\test\\video\private/2021-12-10/1637113276328//1.jpg"
    imagesource = "C:\\test\\docker\\var\\aiparents\\-725156823261342561\\2022-01-25\\1637221775590\\1-recongnized-1.1.jpg"
    img = readImage(imagesource)
    cv2.imshow('copy3', img)
    cv2.waitKey(0)
    img2 = smallPic(img,400)
    cv2.imshow('copy31', img2)
    cv2.waitKey(0)
    img3 = ratiopic(img, 400)
    cv2.imshow('copy312', img3)
    cv2.waitKey(0)
    cv2.destroyAllWindows()